<template>
  <div :class="['engineer', {'engineer-no': shareData.hideTopTip}]"  v-loading="loading">
    <div class="engineer-main">
      <div class="engineer-main-info flex">
        <p class="engineer-name mar-b-14" v-if="providerInfo.providerCode">{{ providerInfo.providerName}}（{{$t('common.base.encode')}}：{{ providerInfo.providerCode }}）</p>
        <div class="flex-x">
          <el-button
            type="primary"
            @click="gotoUrl('PageServiceProviderDetail',providerInfo.tenantProviderId ,`id=${providerInfo.tenantProviderId}`)">
            <span>{{ mainPageTitle }}</span>
          </el-button>
          <template v-if="btnsPerProvider['addEngineerAuth']">
            <el-button
              v-if="tenantType === 1"
              type="plain-third"
              @click="gotoUrl(
           'PageServiceEngineerCreate',
           '' ,
           `tenantProviderId=${providerInfo.tenantProviderId}`)">{{$t('common.base.createEngineer')}}</el-button>
            <el-button
              v-else
              type="plain-third"
              @click="addEngineer">{{$t('common.base.addEngineer')}}</el-button>
          </template>
          <el-button
            v-if="btnsPerProvider['managerEngineerRoleAuth']"
            type="plain-third" @click="openEngineerRule">{{$t('serviceProvider.engineerAuth')}}</el-button>
          <el-dropdown v-if="moreBtnEnable" class="mar-l-12">
            <el-button type="plain-third">{{$t('common.base.more')}}<i class="iconfont icon-fdn-select"></i></el-button>
            <el-dropdown-menu slot="dropdown" class="el-dropdown-provider">
              <el-dropdown-item>
                <div v-if="btnsPerProvider['setProviderAccount']" @click="bulkAllocation">{{$t('serviceProvider.accountsLimit')}}</div>
              </el-dropdown-item>
              <el-dropdown-item>
                <div v-if="!isProviderUser && btnsPerProvider['administerProvider']" @click="setManageProvider">{{$t('common.base.setManager')}}</div>
              </el-dropdown-item>
              <el-dropdown-item>
                <div v-if="btnsPerProvider['addEngineerAuth'] && tenantType === 1" @click="addEngineer">{{$t('serviceProvider.recoverEngAccount')}}</div>
              </el-dropdown-item>
              <el-dropdown-item><div v-if="btnsPerProvider['isMain']" @click="setMainDispatcher">{{$t('common.base.setPrincipal_1')}}</div></el-dropdown-item>
              <el-dropdown-item>
                <div
                  v-if="btnsPerProvider['edit']"
                  @click="gotoUrl('PageServiceProviderEdit',providerInfo.tenantProviderId ,`type=edit&id=${providerInfo.tenantProviderId}`)"
                >
                  {{$t('common.base.edit')}}
                </div>
              </el-dropdown-item>
              <el-dropdown-item>
                <div v-if="btnsPerProvider['delete']" @click="stopProvider">{{$t('common.base.logout')}}</div>
              </el-dropdown-item>
<!--              <el-dropdown-item>
                <div v-if="btnsPerProvider['delete']" @click="delProvider">删除</div>
              </el-dropdown-item>-->
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      
      <div class="engineer-info mar-b-8">
        <div>
          <div class="title">{{$t('common.base.internalAdmin')}}：</div>
          <el-tooltip popper-class="engineer-info-manage-popper" class="engineer-info-manage" placement="left">
          <span
            slot="content"
            class="mar-r-4"
            v-for="(item, index) in providerInfo.internalAdmin"
            :key="index"
            >
            <!-- 部门 -->
            <template v-if="item.objType === 0">{{item.name}}</template>
              <!-- 人员 -->
            <template v-else-if="item.objType === 1">
              <open-data v-if="isOpenData" type="userName" :openid="item.staffId"></open-data>
              <span v-else>{{ item.name }}</span>
            </template>
          </span>
          <div>
            <span
              slot="content"
              class="mar-r-4"
              v-for="(item, index) in providerInfo.internalAdmin"
              :key="index"
            >
              <!-- 部门 -->
              <template v-if="item.objType === 0">{{item.name}}</template>
              <!-- 人员 -->
              <template v-else-if="item.objType === 1">
                <open-data v-if="isOpenData" type="userName" :openid="item.staffId"></open-data>
                <span v-else>{{ item.name }}</span>
              </template>
           </span>
          </div>
          </el-tooltip>
        </div>
        <div>{{$t('common.base.principal')}}：
          <template v-if="providerInfo.mainPrincipal">
           <template v-if="isOpenData && providerInfo.mainPrincipal.staffId">
							<open-data
                  type="userName"
                  :openid="providerInfo.mainPrincipal.staffId"
              ></open-data>
						</template>
						<template v-else>
							<span>{{ providerInfo.mainPrincipal.displayName }}</span>
						</template>
          </template>
        </div>
        <div>{{$t('common.base.tel')}}：{{ providerInfo.providerPhone }}</div>
      </div>
      <div class="engineer-account-info flex-x">
        <div>{{$t('serviceProvider.accountsLimit')}}：{{ providerInfo.accountAllNum || 0 }}</div>
        <div>{{$t('serviceProvider.accountUsed')}}：{{ providerInfo.usedNum || 0 }}</div>
        <div>{{$t('serviceProvider.remainAccounts')}}：{{ (providerInfo.accountAllNum - providerInfo.usedNum) || 0 }}</div>
      </div>
    </div>
    <div class="w-100-p pad-l-12 pad-r-12"><LoginUserBan ref="loginUserBanDom" v-if="haveUserNote" mode="service" :page-info="shareData"></LoginUserBan></div>
    <engineer-list
      ref="engineerList"
      :share-data="shareData">
    </engineer-list>
    <!--设置主负责人-->
    <main-dispatcher ref="mainDisRef" @refresh="resetSearch"></main-dispatcher>
    <!--添加工程师-->
    <add-user ref="addUserRef" @refresh="resetSearch"></add-user>
    <!--设置管理员-->
    <modify-provider-panel ref="modifyRef" @refresh="resetSearch"></modify-provider-panel>
    <!--批量分配-->
    <provider-account ref="providerAccount" @refresh="resetSearch"/>
    <!--角色权限-->
    <base-window size="larger" :unique="false" class-name="provider-role-model" :show.sync="dialogFormVisible" :title="title">
      <roleModule :key="roleModuleKey" :providerId="shareData.tenantProviderId" />
    </base-window>
  </div>
</template>

<script>
import {isOpenData, openAccurateTab} from '@src/util/platform'
import { getRootWindowInitData } from "@src/util/window";
import {PageRoutesTypeEnum} from "@model/enum/PageRoutesEnum";
/* api */
import {
  stopProvider,
  getProviderDataInfo
} from '@src/api/serviceProviderApi';
//component
import roleModule from "@src/modules/account/roleModule/index.js";
import engineerList from '../engineer/engineerList/EngineerList';
import AddUser from '@src/modules/serviceProvider/serviceProviderManage/engineer/component/AddUser'
import MainDispatcher from '@src/modules/serviceProvider/serviceProviderManage/engineer/component/MainDispatcher'
import ModifyProviderPanel from '@src/modules/dept/component/ModifyProviderPanel';
import ProviderAccount from "@src/modules/serviceProvider/serviceProviderManage/component/ProviderAccount.vue";

import LoginUserBan from '@src/modules/dept/component/loginUserBan.vue'

import { useStateNoteUserSendMessage } from '@src/modules/dept/mock.ts'
const { haveUserNote } = useStateNoteUserSendMessage()

export default {
  name: "EngineerMain",
  components: {
    engineerList,
    roleModule,
    AddUser,
    MainDispatcher,
    ModifyProviderPanel,
    ProviderAccount,
    LoginUserBan,
  },
  props: {
    shareData: {
      type: Object,
      default: () => ({})
    }
  },
  computed:{
    // 是否是服务商
    isProviderUser() {
      return getRootWindowInitData().isProviderUser || false
    },
    // 0：钉钉端，1：自建，2：企微端
    tenantType() {
      return getRootWindowInitData().tenantType;
    },
    // 我的主页/服务商主页
    mainPageTitle() {
      return this.isProviderUser ? this.$t('common.pageTitle.pageMyHome') : this.$t('common.pageTitle.pageServiceProviderViewHome')
    },
    moreBtnEnable() {
      return ((!this.isProviderUser && this.btnsPerProvider['administerProvider'])
          || (this.btnsPerProvider['addEngineerAuth'] && this.tenantType === 1)
          || ['isMain', 'edit', 'delete', 'setProviderAccount'].includes(this.btnsPerProvider))
    },
  },
  data() {
    return {
      isOpenData,
      providerInfo: {},
      btnsPerProvider: {}, // 服务商按钮权限
      loading: false,
      roleModuleKey:0,
      // 角色权限弹框
      dialogFormVisible: false,
      title: this.$t('conmmon.base.serviceProvider'),
      haveUserNote,
    };
  },
  methods: {
    // 打开工程师角色
    openEngineerRule() {
      this.dialogFormVisible = true;
      this.title = this.shareData?.name || this.$t('conmmon.base.serviceProvider')
    },
    // 删除服务商
    async delProvider() {
      try {
        await this.$confirm(this.$t('serviceProvider.accountTip.tip17'), this.$t('serviceProvider.accountTip.tip16'));
      } catch (e) {
        console.error(e)
      }
    },
    // 注销服务商
    async stopProvider() {
      try {
        if(this.providerInfo?.status === '0') { // 服务商已注销
          return this.$message.warning({
            message: this.$t('serviceProvider.providerIsLogout'),
            showClose: true,
            duration: 2000,
          });
        }
        await this.$confirm(this.$t('serviceProvider.providerLogout'), this.$t('serviceProvider.logoutTip'));
        let res = await stopProvider({tenantProviderId: this.providerInfo?.tenantProviderId});
        this.$notify({
          title: this.$t('common.base.toast'),
          type: res.success ? 'success' : 'error',
          message: res.success ? this.$t('common.base.logoutSuccess') : res.message,
          showClose: true,
          duration: 2000,
        });
        // 刷新整个页面，注销完成以后返回到服务商树下面
        this.$emit('refresh');
      } catch (e) {
        console.error(e);
      }
    },

    // 获取服务商基本信息
    async getProviderDataInfo(tenantProviderId) {
      try {
        this.loading = true;
        let res = await getProviderDataInfo({tenantProviderId, isProviderUser: this.isProviderUser});
        if(res.success && res.code === 0) {
          this.providerInfo = res?.result?.providerInfoVO || {};
          res?.result?.buttonAuth?.forEach(item => {
            this.$set(this.btnsPerProvider, item.type, item.visible)
          });// 按钮权限
        }
      } catch (e) {
        console.error(e);
      } finally {
        this.loading = false;

      }
    },

    refresh() {
      this.$emit('refresh', 'provider');
    },

    gotoUrl(type, key = '', params = '') {
      let fromId = window.frameElement.getAttribute('id');
      openAccurateTab({
        type: PageRoutesTypeEnum[type],
        key,
        params,
        fromId
      });
    },

    // 添加工程师（钉钉端）
    addEngineer() {
      let provide = {}
      if(this.shareData?.tenantProviderId) {
        provide = {
          label: this.shareData?.name,
          value: this.shareData?.tenantProviderId,
        }
      }
      this.$refs?.addUserRef?.openDialog(provide);
    },

    //设主派单员
    async setMainDispatcher() {
      this.$refs.mainDisRef?.openDialog(this.shareData?.tenantProviderId);
    },

    // 刷新
    resetSearch() {
      this.getProviderDataInfo(this.shareData?.tenantProviderId) // 添加工程师以后需要刷新服务商信息，因为账号数量改了
      this.$refs.engineerList?.resetSearch(); // 刷新工程师列表
      this.$refs.loginUserBanDom.initData();
    },

    // 设置管理员
    setManageProvider() {
      // 拼接服务商信息
      let providerInfo = {
        providerCode: this.providerInfo?.providerCode || '',
        providerName: this.providerInfo?.providerName || '',
        contacts: this.providerInfo?.providerPeople || '',
        providerPhone: this.providerInfo?.providerPhone || '',
        id: this.shareData?.tenantProviderId
      }
      this.$refs.modifyRef?.open(providerInfo)
    },

    // 分配账号数量
    bulkAllocation() {
      this.$refs?.providerAccount?.openDialog([this.shareData?.tenantProviderId], false)
    },
  },
  watch: {
    shareData:{
      immediate: true,
      deep: true,
      handler(val) {
        if(val.tenantProviderId) {
          this.roleModuleKey = Date.now()
          // 查询服务商信息
          this.getProviderDataInfo(val.tenantProviderId);
          this.$nextTick(()=>{
            this.$refs.loginUserBanDom.initData();
          })
          
        }
      }
    }
  },
}
</script>

<style scoped lang="scss">
.engineer {
  height: calc(100vh - 80px);
  overflow: auto;
  .engineer-main {
    background: white;
    padding: 20px 17px 18px 16px;
    margin: 0 16px 16px 0;
    justify-content: space-between;
    border-radius: 4px;
    .engineer-main-info {
      flex-grow: 1;
      justify-content: space-between;
      margin-bottom: 16px;
      .engineer-name {
        height: 24px;
        font-size: 16px;
        font-weight: 500;
        color: $text-color-primary;
        line-height: 24px;
      }
      .icon-fdn-select {
        margin-right: 0;
        margin-left: 4px;
      }
    }
    .engineer-info {
      display: flex;
      > div {
        display: flex;
        width: 30%;
        margin-right: 16px;
        .title {
          flex-shrink: 0;
        }
      }
    }
    .engineer-info-manage {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .engineer-account-info div{
      width: 30%;
      margin-right: 16px;
      display: inline-block;
    }
  }
  .main-tab {
    background: white;
    margin-right: 12px;
    border-radius: 4px;
    .service-list {
      height: calc(100vh - 78px);
    }
    ::v-deep .el-tabs__header {
      margin-left: 16px;
    }
  }
}
.engineer-no {
  height: calc(100vh - 30px);
}
</style>
<style lang="scss">
.main-tab .el-tabs__content {
   overflow: visible !important;
}
.provider-role-model {
  .base-window-content-body {
    padding: 4px;
    height: 100%;
    overflow: hidden;
    .role-management-view {
      padding: 0;
    }
  }
  .base-window-content-footer {
    display: none;
  }
}
.engineer-info-manage-popper {
  max-width: 150px;
}
</style>